<?php
namespace App\Listener\User;

use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Event\Annotation\Listener;

use App\Query\OrderQuery;
use App\Repository\OrderRepository;

/**
 * @Listener 
 */
class OrderMoneyRemainListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            \App\Event\User\OrderMoneyRemainEvent::class,
        ];
    }
    
    // 用户循环释放指定积分
    public function process($event)
    {
        // 已释放金额
        $remain = 0;
        
        // 仓库
        $repository = OrderRepository::make();
        
        // 获取用户所有可释放的订单
        $orders = OrderQuery::remain(OrderQuery::user($event->user))->get();

        
        foreach($orders as $order)
        {
            $repository->model($order);
            
            // 累加释放的金额
            $remain = bcadd($remain, $repository->makeMoneyRemain(bcsub($event->money, $remain)), 2);
            
            // 如果完成了，就跳出循环
            if($event->money <= $remain)
            {
                break;
            }
        }
        
        // 积分按比例归入帐户
        $event->user->orderMoneyRemainUser($event->type, $remain, $event->content);
    }
}